<template>
  <div class="dashboard-container">
    <div class="dashboard-header">
      <h1>项目看板</h1>
    </div>

    <div class="metrics-grid">
      <!-- 项目总金额卡片 -->
      <div class="metric-card" @click="toggleAllStats">
        <div class="metric-title">
          项目总金额
          <span class="expand-icon">{{ showAllStats ? '▼' : '▶' }}</span>
        </div>
        <div class="metric-value">¥{{ formatNumber(dashboardData.totalAmount) }}</div>

        <!-- 客户合同金额子表 -->
        <div v-if="showAllStats" class="customer-stats-table">
          <div class="table-header">
            <span class="customer-col">客户名称</span>
            <span class="amount-col">合同金额</span>
          </div>
          <div class="table-body">
            <div
              v-for="(customer, index) in dashboardData.customerStats"
              :key="index"
              class="table-row"
            >
              <span class="customer-col">{{ customer.customerName }}</span>
              <span class="amount-col">¥{{ formatNumber(customer.totalContractAmount) }}</span>
            </div>
          </div>
        </div>
      </div>

      <!-- 已收金额卡片 -->
      <div class="metric-card" @click="toggleAllStats">
        <div class="metric-title">
          已收金额
          <span class="expand-icon">{{ showAllStats ? '▼' : '▶' }}</span>
        </div>
        <div class="metric-value">¥{{ formatNumber(dashboardData.receivedAmount) }}</div>

        <!-- 客户已收金额子表 -->
        <div v-if="showAllStats" class="customer-stats-table">
          <div class="table-header">
            <span class="customer-col">客户名称</span>
            <span class="amount-col">已收金额</span>
          </div>
          <div class="table-body">
            <div
              v-for="(customer, index) in dashboardData.customerReceivedStats"
              :key="index"
              class="table-row"
            >
              <span class="customer-col">{{ customer.customerName }}</span>
              <span class="amount-col">¥{{ formatNumber(customer.receivedAmount) }}</span>
            </div>
          </div>
        </div>
      </div>

      <!-- 未收金额卡片 -->
      <div class="metric-card" @click="toggleAllStats">
        <div class="metric-title">
          未收金额
          <span class="expand-icon">{{ showAllStats ? '▼' : '▶' }}</span>
        </div>
        <div class="metric-value">¥{{ formatNumber(dashboardData.pendingAmount) }}</div>

        <!-- 客户未收金额子表 -->
        <div v-if="showAllStats" class="customer-stats-table">
          <div class="table-header">
            <span class="customer-col">客户名称</span>
            <span class="amount-col">未收金额</span>
          </div>
          <div class="table-body">
            <div
              v-for="(customer, index) in dashboardData.customerPendingStats"
              :key="index"
              class="table-row"
            >
              <span class="customer-col">{{ customer.customerName }}</span>
              <span class="amount-col">¥{{ formatNumber(customer.pendingAmount) }}</span>
            </div>
          </div>
        </div>
      </div>

      <!-- 项目总数卡片 -->
      <div class="metric-card" @click="toggleAllStats">
        <div class="metric-title">
          项目总数
          <span class="expand-icon">{{ showAllStats ? '▼' : '▶' }}</span>
        </div>
        <div class="metric-value">{{ dashboardData.projectCount }}</div>

        <!-- 客户项目数量子表 -->
        <div v-if="showAllStats" class="customer-stats-table">
          <div class="table-header">
            <span class="customer-col">客户名称</span>
            <span class="amount-col">项目数量</span>
          </div>
          <div class="table-body">
            <div
              v-for="(customer, index) in dashboardData.customerProjectStats"
              :key="index"
              class="table-row"
            >
              <span class="customer-col">{{ customer.customerName }}</span>
              <span class="amount-col">{{ customer.projectCount }}</span>
            </div>
          </div>
        </div>
      </div>
    </div>

    <div class="presales-section">
      <div class="presales-card">
        <div class="presales-title">售前项目总金额</div>
        <div class="presales-value">¥{{ formatNumber(dashboardData.preSalesTotalAmount) }}</div>
      </div>
      <div class="presales-card">
        <div class="presales-title">售前项目数量</div>
        <div class="presales-value">{{ dashboardData.preSalesProjectCount }}</div>
      </div>
    </div>

    <div class="status-section">
      <h2>项目状态分布</h2>
      <div class="status-cards">
        <div class="status-card">
          <div class="status-title">规划中</div>
          <div class="status-number">{{ dashboardData.statusDistribution.planning }}</div>
        </div>
        <div class="status-card">
          <div class="status-title">进行中</div>
          <div class="status-number">{{ dashboardData.statusDistribution.active }}</div>
        </div>
        <div class="status-card">
          <div class="status-title">已暂停</div>
          <div class="status-number">{{ dashboardData.statusDistribution.suspended }}</div>
        </div>
        <div class="status-card">
          <div class="status-title">已完成</div>
          <div class="status-number">{{ dashboardData.statusDistribution.completed }}</div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { getDashboardData, getPreSalesDashboard } from '@/api/dashboard/dashboard'

export default {
  name: 'Dashboard',
  data() {
    return {
      trendPeriod: '30days',
      // 统一控制所有卡片的子表显示状态
      showAllStats: false,
      dashboardData: {
        totalAmount: 0,
        receivedAmount: 0,
        pendingAmount: 0,
        receivedRate: 0,
        pendingCount: 0,
        projectCount: 0,
        activeCount: 0,
        preSalesTotalAmount: 0,
        preSalesProjectCount: 0,
        customerStats: [], // 客户合同金额统计
        customerProjectStats: [], // 客户项目数量统计
        customerReceivedStats: [], // 客户已收金额统计
        customerPendingStats: [], // 客户未收金额统计
        statusDistribution: {
          planning: 0,
          active: 0,
          completed: 0,
          suspended: 0
        }
      },
    }
  },
  methods: {
    // 切换所有统计子表的显示
    toggleAllStats() {
      this.showAllStats = !this.showAllStats;
    },

    // 获取后台数据
    async fetchDashboardData() {
      try {
        // 请求项目看板（包含 active/suspended/completed）
        const projectRes = await getDashboardData();
        if (projectRes.code === 200) {
          // 请求售前项目看板（planningCount）
          let planningCount = 0;
          try {
            const preSalesRes = await getPreSalesDashboard();
            if (preSalesRes.code === 200) {
              this.dashboardData.preSalesTotalAmount = preSalesRes.data.totalAmount || 0;
              this.dashboardData.preSalesProjectCount = preSalesRes.data.projectCount || 0;
              planningCount = preSalesRes.data.planningCount || 0;
            }
          } catch (err) {
            console.warn('售前项目看板加载失败', err);
          }

          // 更新状态分布，用售前的 planningCount 替换 planning，其它状态保留原数据
          const statusDistribution = {
            planning: planningCount,
            active: projectRes.data.statusDistribution?.active || 0,
            completed: projectRes.data.statusDistribution?.completed || 0,
            suspended: projectRes.data.statusDistribution?.suspended || 0
          };

          this.dashboardData = {
            ...this.dashboardData,
            totalAmount: projectRes.data.totalAmount || 0,
            receivedAmount: projectRes.data.receivedAmount || 0,
            pendingAmount: projectRes.data.pendingAmount || 0,
            receivedRate: projectRes.data.receivedRate || 0,
            pendingCount: projectRes.data.pendingCount || 0,
            projectCount: projectRes.data.projectCount || 0,
            activeCount: projectRes.data.activeCount || 0,
            customerStats: projectRes.data.customerStats || [], // 客户合同金额统计
            customerProjectStats: projectRes.data.customerProjectStats || [], // 客户项目数量统计
            customerReceivedStats: projectRes.data.customerReceivedStats || [], // 客户已收金额统计
            customerPendingStats: projectRes.data.customerPendingStats || [], // 客户未收金额统计
            statusDistribution
          };
        } else {
          this.$message.error(projectRes.msg || '加载项目看板失败');
        }

      } catch (err) {
        console.error('项目看板加载失败', err);
        this.$message.error('看板数据加载失败');
      }
    },
    formatNumber(num) {
      if (!num) return 0
      return Number(num).toLocaleString()
    },
  },
  mounted() {
    this.fetchDashboardData()
  }
}
</script>

<style lang="scss" scoped>
.dashboard-container {
  padding: 24px;
  background: #ffffff;
  min-height: calc(100vh - 84px);
}

.dashboard-header {
  margin-bottom: 32px;

  h1 {
    font-size: 32px;
    font-weight: 600;
    color: #1a1a1a;
    margin: 0;
  }
}

.metrics-grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 24px;
  margin-bottom: 32px;
}

.metric-card {
  background: #ffffff;
  padding: 32px 24px;
  border: 1px solid #e5e7eb;
  border-radius: 8px;
  text-align: center;
  transition: all 0.2s ease;
  position: relative;
  cursor: pointer; // 添加手型光标

  &:hover {
    border-color: #d1d5db;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  }

  .metric-title {
    font-size: 14px;
    color: #6b7280;
    margin-bottom: 12px;
    font-weight: 500;
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 8px;

    .expand-icon {
      font-size: 12px;
      color: #9ca3af;
    }
  }

  .metric-value {
    font-size: 28px;
    font-weight: 700;
    color: #111827;
  }
}

// 客户统计子表样式
.customer-stats-table {
  margin-top: 20px;
  border: 1px solid #e5e7eb;
  border-radius: 6px;
  overflow: hidden;
  background: #f9fafb;

  .table-header {
    display: flex;
    background: #f3f4f6;
    padding: 12px 16px;
    font-size: 12px;
    font-weight: 600;
    color: #374151;
    border-bottom: 1px solid #e5e7eb;

    .customer-col {
      flex: 2;
      text-align: left;
    }

    .amount-col {
      flex: 1;
      text-align: right;
    }
  }

  .table-body {
    max-height: 200px;
    overflow-y: auto;

    .table-row {
      display: flex;
      padding: 10px 16px;
      font-size: 12px;
      border-bottom: 1px solid #f3f4f6;
      background: white;

      &:last-child {
        border-bottom: none;
      }

      &:hover {
        background: #f9fafb;
      }

      .customer-col {
        flex: 2;
        text-align: left;
        color: #374151;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
      }

      .amount-col {
        flex: 1;
        text-align: right;
        color: #111827;
        font-weight: 500;
      }
    }
  }
}

.presales-section {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 24px;
  margin-bottom: 32px;
}

.presales-card {
  background: #ffffff;
  padding: 32px 24px;
  border: 1px solid #e5e7eb;
  border-radius: 8px;
  text-align: center;
  transition: all 0.2s ease;

  &:hover {
    border-color: #d1d5db;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  }

  .presales-title {
    font-size: 14px;
    color: #6b7280;
    margin-bottom: 12px;
    font-weight: 500;
  }

  .presales-value {
    font-size: 24px;
    font-weight: 700;
    color: #111827;
  }
}

.status-section {
  background: #ffffff;
  padding: 32px;
  border: 1px solid #e5e7eb;
  border-radius: 8px;

  h2 {
    font-size: 20px;
    font-weight: 600;
    color: #111827;
    margin: 0 0 24px 0;
  }
}

.status-cards {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 16px;
}

.status-card {
  background: #f9fafb;
  padding: 24px;
  border: 1px solid #e5e7eb;
  border-radius: 8px;
  text-align: center;
  transition: all 0.2s ease;

  &:hover {
    background: #f3f4f6;
    border-color: #d1d5db;
  }

  .status-title {
    font-size: 14px;
    color: #6b7280;
    margin-bottom: 8px;
    font-weight: 500;
  }

  .status-number {
    font-size: 24px;
    font-weight: 700;
    color: #111827;
  }
}

@media (max-width: 768px) {
  .metrics-grid {
    grid-template-columns: repeat(2, 1fr);
  }

  .presales-section {
    grid-template-columns: 1fr;
  }

  .status-cards {
    grid-template-columns: repeat(2, 1fr);
  }

  .customer-stats-table {
    .table-header,
    .table-row {
      padding: 8px 12px;
      font-size: 11px;
    }
  }
}
</style>
